import axios from 'axios';
import { message } from 'antd';
import getToken from './token';
import { getRequestConfig } from './config';
import { err401, Respone, unknownError } from './respone';
import userStore from '@/models/user';

// parse error
export function parseError(errors: API.BasicError[]) {
  const [error] = errors;
  const code = error?.extensions?.code;

  switch (code) {
    case 'PERMISSION_DENIED': {
      return err401;
    }
  }

  return new Respone(
    unknownError.code,
    error.message ||
    unknownError.message
  );
}

async function request<R = any>(payload: API.RequestPayload): Promise<R> {
  const {
    url = '',
    platform,
    skipToken = false,
    ...input
  } = payload;

  const config = getRequestConfig(platform);

  const instance = axios.create({
    baseURL: config.apiUrl,
    headers: { 'x-app-id': config.appId }
  });

  let headers: Record<string, any> = {};

  try {
    // 获取 token 逻辑
    if (!skipToken) {
      headers = {
        Authorization: await getToken()
      }
      if (!headers.Authorization) {
        throw err401;
      }
    }

    const result = await instance.post<API.BasicRes<R>>(
      url, input, { headers }
    );

    const resData = result.data;
    const errors = resData?.errors || [];

    // 存在错误
    if (errors.length) {
      const error = parseError(errors)
      return Promise.reject(error);
    }

    return resData.data;
  } catch (err) {
    if (err instanceof Respone) {
      // 登录失效
      if (err.code === err401.code) {
        userStore.getState().logout();
        message.warning('登录失效!');
      }
      return Promise.reject(err);
    } else {
      return Promise.reject(unknownError);
    }
  }
}

export default request;